<template>
	<view class="my-container tabbar_container">
		<uv-toast ref="myToast"></uv-toast>
		<!-- 顶部用户信息卡片 -->
		<view class="user-card"
			:style="{ background: userInfo.openId ? 'linear-gradient(135deg, #007AFF, #0056b3)' : 'linear-gradient(135deg, #ffc107, #ff9a2f);' }">
			<!-- 背景图层 -->
			<view class="card-bg" :style="backgroundStyle">
				<!-- 遮罩层 -->
				<view class="mask-layer"></view>
			</view>
			<view class="user-info">
				<view class="avatar-wrapper">
					<image class="avatar" :src="userInfo.avatarUrl || userInfo.image || '/static/avatar_man.png'" />
					<view class="avatar-badge" v-if="userInfo.verified === 1 || userInfo.image">
						<uv-icon name="checkmark" size="12" color="#fff"></uv-icon>
					</view>
				</view>
				<view class="info-right">
					<view class="nickname-wrap">
						<text class="nickname">{{ userInfo.merchantName || userInfo.nikeName || '未登录' }}</text>
						<view class="auth-tag" v-if="userInfo.merchantName || userInfo.nikeName">
							<text v-if="userInfo.merchantName" :class="userInfo.image ? 'verified' : 'unverified'">
								{{ userInfo.image ? '图片已上传' : '未上传图片' }}
							</text>
							<text v-else :class="userInfo.verified === 1 ? 'verified' : 'unverified'">
								{{ userInfo.verified === 1 ? '已认证' : '未认证' }}
							</text>
						</view>
					</view>
					<view v-if="userInfo.merchantName || userInfo.nikeName" class="user-id">
						<text>{{ userInfo.phone || '--' }}</text>
					</view>
					<view v-else class="login-btn" @click.stop="goToLogin">
						<text>立即登录</text>
						<uv-icon name="arrow-right" size="24" color="#fff"></uv-icon>
					</view>
				</view>
			</view>
			<!-- 身份切换按钮 -->
			<view class="role-switch" v-if="showRoleAction" @click.stop="handleRoleAction">
				<uv-icon name="reload" size="26" color="#fff"></uv-icon>
				<text>{{ roleActionText }}</text>
			</view>
		</view>

		<!-- 用户数据统计卡片 -->
		<view class="stats-card" v-if="userInfo.nikeName">
			<view class="stat-item" @tap="goToCoupons">
				<text class="value">{{ couponCount || 0 }}</text>
				<text class="label">餐券</text>
			</view>
			<view class="stat-item" @tap="goToCourses">
				<text class="value">{{ pendingOrderCount || 0 }}</text>
				<text class="label">课程</text>
			</view>
			<view class="stat-item">
				<text class="value">{{ userInfo.points || 0 }}</text>
				<text class="label">积分</text>
			</view>
		</view>

		<!-- 绑定商家信息 -->
		<view class="binding-merchant">
			<MerchantInfoEasyCard :merchantId="userInfo.registrationShop"></MerchantInfoEasyCard>
		</view>

		<!-- 商家特定信息 -->
		<view class="store-info" v-if="userInfo.merchantName">
			<view class="store-detail">
				<view class="store-name">{{ userInfo.name }}</view>
				<view class="store-address">
					<uv-icon name="map" size="28" color="#666"></uv-icon>
					<text>{{ formatAddress }}</text>
				</view>
				<view class="store-time" v-if="userInfo.openingHours">
					<uv-icon name="clock" size="28" color="#666"></uv-icon>
					<text>营业时间：{{ userInfo.openingHours }}</text>
				</view>
				<view class="store-director" v-if="userInfo.director">
					<uv-icon name="account" size="28" color="#666"></uv-icon>
					<text>负责人：{{ userInfo.director }}</text>
				</view>
			</view>
			<view class="store-stats">
				<view class="stat-item">
					<text class="number">{{ todayCoupons }}</text>
					<text class="label">今日领券</text>
				</view>
				<view class="stat-item">
					<text class="number">{{ totalCoupons }}</text>
					<text class="label">总领券数</text>
				</view>
			</view>
		</view>

		<!-- 功能菜单 -->
		<view class="menu-section">
			<!-- 商家菜单 -->
			<template v-if="userInfo.merchantName">
				<MerchantMenuGroup :merchantId="userInfo.id" />
			</template>

			<!-- 用户菜单 -->
			<template v-else>
				<UserMenuGroup />
			</template>
		</view>

		<!-- 轮播图只在有广告且是普通用户时显示 -->
		<view class="swiper" v-if="advertisementList.length > 0 && (userInfo.openId || !userInfo.id)">
			<uv-swiper :list="advertisementList" indicator indicatorMode="line" height="264" circular class="swiper"
				radius="10"></uv-swiper>
		</view>

		<view v-if="userInfo.id" class="login-out-container" @click="loginOut">
			<uv-icon name="loginout" size="30" color="#3c9cff" custom-prefix="custom-icon"></uv-icon>
			<text>退出登录</text>
		</view>

		<CustomTabBar selected="3" />
	</view>
</template>

<script>
import {
	isUserLoggedIn
} from '@/plugins/auth.js'
export default {
	data() {
		return {
			scroll: 0,
			userInfo: {},
			bindingMerchant: {},
			couponCount: 0,
			points: 0,
			storeName: '未绑定门店',
			balance: 0,
			storeAddress: '',
			todayCoupons: 0,
			totalCoupons: 0,
			pendingOrderCount: 0,
			showRoleAction: false,
			roleActionText: '',
			advertisementList: [], // 广告列表
		}
	},
	computed: {
		// 格式化地址
		formatAddress() {
			if (!this.userInfo.merchantName) return '';
			const address = [];
			if (this.userInfo.province) address.push(this.userInfo.province);
			if (this.userInfo.city) address.push(this.userInfo.city);
			if (this.userInfo.district) address.push(this.userInfo.district);
			if (this.userInfo.street) address.push(this.userInfo.street);
			return address.join(' ') || '暂无地址信息';
		},
		backgroundStyle() {
			if (this.userInfo.merchantName && this.userInfo.image) {
				return {
					backgroundImage: `url(${this.userInfo.image})`,
					backgroundSize: 'cover',
					backgroundPosition: 'center'
				}
			}
			return {}
		}
	},
	methods: {
		// 显示提示信息
		showToast(msg, type = 'default', duration = 1000) {
			this.$refs.myToast.show({
				message: msg,
				type: type,
				duration: duration,
			})
		},
		goToCoupons() {
			uni.navigateTo({
				url: '/subpkg/coupon/coupon'
			})
		},
		goToCourses() {
			uni.navigateTo({
				url: '/subpkg/my_courses/my_courses'
			})
		},
		goToEditInfo() {
			uni.navigateTo({
				url: '/subpkg/edit_merchant_info/edit_merchant_info'
			})
		},
		goToQRCode() {
			uni.navigateTo({
				url: '/subpkg/create_qccode/create_qccode'
			})
		},
		goToAccount() {
			if (!this.userInfo.id) {
				uni.navigateTo({
					url: '/subpkg/login_page/login_page'
				})
				return;
			}
			uni.navigateTo({
				url: '/subpkg/profile/profile'
			})
		},
		async loginOut() {
			try {
				// 根据用户信息判断登出类型
				const loginType = this.userInfo.merchantName ? 'MERCHANT' : 'MINI_PROGRAM'

				// 发送登出请求
				const res = await this.$http.get(`/auth/logout?loginType=${loginType}`)

				if (res) {
					// 清除本地存储的token
					if (loginType === 'MERCHANT') {
						uni.removeStorageSync('shop_token')
					} else {
						uni.removeStorageSync('token')
					}

					// 提示成功
					uni.showToast({
						title: '退出成功',
						icon: 'success',
						duration: 1500
					})

					// 延迟跳转到登录页
					setTimeout(() => {
						uni.reLaunch({
							url: `/subpkg/login_page/login_page?mode=${loginType === 'MERCHANT' ? '1' : '0'}`
						})
					}, 1500)
				}
			} catch (e) {
				console.error('退出登录失败', e)
				this.showToast('退出失败，请重试', 'error', 2000)
			}
		},
		async getUserInfo() {
			try {
				const res = await this.$http.post('/auth/mini/profile');
				if (res) {
					this.userInfo = res;
					// 获取用户信息后立即获取广告
					await this.fetchAdvertisements();
				}
			} catch (error) {
				this.showToast(error.msg, 'error', 1000);
			}
		},
		async getMerchantInfo() {
			try {
				const res = await this.$http.post('/auth/merchant/info');

				if (res) {
					this.userInfo = res;
				}
			} catch (e) {
				this.showToast(e.msg, 'error', 1000);
			}
		},
		async getMerchantStats() {
			try {
				// 获取今日店铺统计数据
				const res = await this.$http.get(
					`/analytics/coupon/merchant/stats?merchantIds=${this.userInfo.id}`)

				if (res && res.length > 0) {
					this.todayCoupons = res[0].todayCouponCount || 0
					this.totalCoupons = res[0].totalCouponCount || 0
				}
			} catch (error) {
				console.error('获取店铺统计失败', error)
			}
		},
		goToVerifyCoupon() {
			uni.navigateTo({
				url: `/subpkg/verify_breakfast_coupon/verify_breakfast_coupon?merchantId=${this.userInfo.id}`
			})
		},
		goToCouponStats() {
			uni.navigateTo({
				url: `/subpkg/coupon_stats/coupon_stats?merchantId=${this.userInfo.id}`
			})
		},
		goToStore() {
			uni.navigateTo({
				url: '/subpkg/store_info/store_info'
			})
		},
		goToOrders() {
			uni.navigateTo({
				url: '/subpkg/orders/orders'
			})
		},
		goToLogin() {
			uni.navigateTo({
				url: '/subpkg/login_page/login_page'
			})
		},
		async checkLoginStatus() {
			const userToken = uni.getStorageSync('token')
			const shopToken = uni.getStorageSync('shop_token')

			this.showRoleAction = true // 默认显示操作按钮

			if (shopToken && userToken) {
				// 两个token都存在时，根据mode参数决定显示哪个身份
				const pages = getCurrentPages()
				const currentPage = pages[pages.length - 1]
				const mode = currentPage.options.mode || '0'
				await this.fetchUserInfo(mode)
			} else if (shopToken) {
				// 只有商家token
				await this.fetchUserInfo('1')
			} else if (userToken) {
				// 只有用户token
				await this.fetchUserInfo('0')
			} else {
				// 都没有token时隐藏按钮
				this.showRoleAction = false
			}

			// 根据用户信息设置角色和按钮文本
			this.updateRoleInfo()
		},

		updateRoleInfo() {
			if (this.userInfo.merchantName) {
				// 商家身份
				this.userInfo.role = 'merchant'
				this.roleActionText = uni.getStorageSync('token') ? '切换到用户身份' : '登录用户端'
			} else if (this.userInfo.openId) {
				// 普通用户身份
				this.userInfo.role = 'user'
				this.roleActionText = uni.getStorageSync('shop_token') ? '切换到商家身份' : '商家登录'
			}
		},

		async fetchUserInfo(mode) {
			try {
				if (mode === '1') {
					// 获取商户信息
					const res = await this.$http.post('/auth/merchant/info')
					if (res) {
						this.userInfo = {
							...res,
							role: 'merchant' // 添加角色标识
						}
						// 获取店铺统计数据
						await this.getMerchantStats()
					}
				} else {
					// 获取用户信息
					const res = await this.$http.post('/auth/mini/profile')
					if (res) {
						this.userInfo = {
							...res,
							role: 'user' // 添加角色标识
						}
					}
				}
				// 更新角色信息
				this.updateRoleInfo()
			} catch (error) {
				this.showToast(error.msg, 'default', 1000);
			}
		},
		async handleRoleAction() {
			const userToken = uni.getStorageSync('token')
			const shopToken = uni.getStorageSync('shop_token')

			if (shopToken && userToken) {
				// 两个token都存在，执行切换操作
				const newRole = this.userInfo.merchantName ? 'user' : 'merchant'
				const mode = newRole === 'merchant' ? '1' : '0'

				// 重新加载页面并传递mode参数
				uni.reLaunch({
					url: `/pages/my/index?mode=${mode}`
				})
			} else if (this.userInfo.merchantName) {
				// 当前是商家，跳转到用户登录
				uni.navigateTo({
					url: '/subpkg/login_page/login_page?mode=0'
				})
			} else {
				// 当前是用户，跳转到商家登录
				uni.navigateTo({
					url: '/subpkg/login_page/login_page?mode=1'
				})
			}
		},
		goToEditInfo() {
			uni.navigateTo({
				url: '/subpkg/edit_merchant_info/edit_merchant_info'
			})
		},
		async fetchBreakCouponCount() {
			const userToken = uni.getStorageSync('token')
			if (!userToken) {
				return;
			}
			try {
				const couponCount = await this.$http.post('/breakfast/coupon/count');
				this.couponCount = couponCount;
			} catch (e) {
				this.showToast('早餐券加载失败', 'default', 1000);
			}
		},
		// 获取广告信息
		async fetchAdvertisements() {
			try {
				if (!this.userInfo.registrationShop) return;

				const res = await this.$http.get(
					`/advertisement/merchant/active?merchantId=${this.userInfo.registrationShop}`);

				if (res && Array.isArray(res)) {
					// 只提取imageUrl到轮播图列表
					this.advertisementList = res
						.filter(item => item.imageUrl || item.image) // 过滤掉没有图片的广告
						.map(item => item.imageUrl || item.image); // 提取图片URL
				}
			} catch (error) {
				console.error('获取广告信息失败:', error);
				this.advertisementList = [];
			}
		},

		async fetchOrderCount() {
			if (!isUserLoggedIn()) {
				return;
			}
			try {
				const data = await this.$http.get('/order/count');
				if (data) {
					this.pendingOrderCount = data;
				}
			} catch (e) {
				console.error('获取订单数量失败');
			}
		},

		// 添加下拉刷新的生命周期方法
		async onPullDownRefresh() {
			try {
				// 根据当前角色重新获取用户信息
				const mode = this.userInfo.merchantName ? '1' : '0'
				await this.fetchUserInfo(mode)
				// 刷新其他数据
				await Promise.all([
					this.fetchBreakCouponCount(),
					this.fetchOrderCount()
				])
			} catch (e) {
				this.handleError(e, '刷新失败')
			} finally {
				// 停止下拉刷新动画
				uni.stopPullDownRefresh()
			}
		},

		// 统一处理错误
		handleError(e, defaultMsg) {
			uni.showToast({
				title: e.msg || defaultMsg,
				icon: 'none'
			})
		}
	},
	onLoad(options) {
		this.scroll = uni.getWindowInfo().windowHeight + 'px'
		// 根据options.mode初始化页面
		if (options.mode) {
			this.checkLoginStatus()
		}
	},

	onShow() {
		// 如果不是通过mode参数加载，则正常检查登录状态
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		if (!currentPage.options.mode) {
			this.checkLoginStatus()
		}
		this.fetchBreakCouponCount();
		this.fetchOrderCount();
	},
	// 监听用户信息变化
	watch: {
		'userInfo.registrationShop': {
			handler(newVal) {
				if (newVal) {
					this.fetchAdvertisements();
				} else {
					this.advertisementList = [];
				}
			},
			immediate: true
		}
	}
}
</script>

<style lang="scss">
page {
	background-color: #f5f6fa;
}
</style>

<style lang="scss" scoped>
@import './index.scss';
</style>